package com.chc.web.user.service.impl;

import com.chc.web.user_role.entity.UserRole;
import com.chc.web.user_role.mapper.UserRoleMapper;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chc.web.user.entity.User;
import com.chc.web.user.entity.UserParm;
import com.chc.web.user.mapper.UserMapper;
import com.chc.web.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2021/12/19/21:23
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public IPage<User> list(UserParm param) {

        IPage<User> page = new Page<>();
        page.setSize(param.getPageSize());
        page.setCurrent(param.getCurrentPage());

        QueryWrapper<User> query = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(param.getPhone())){
            query.lambda().like(User::getPhone,param.getPhone());
        }
        if (StringUtils.isNotEmpty(param.getUserName())){
            query.lambda().like(User::getUsername,param.getUserName());
        }

        return this.baseMapper.selectPage(page,query);
    }

    @Override
    public UserRole getRoleByUserId(UserRole userRole) {
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.lambda().eq(UserRole::getUserId,userRole.getUserId());
        return userRoleMapper.selectOne(query);
    }

    @Override
    @Transactional
    public void saveRole(UserRole userRole) {
        //删除原来的角色
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.lambda().eq(UserRole::getUserId,userRole.getUserId());
        userRoleMapper.delete(query);
        //保存新角色
        userRoleMapper.insert(userRole);
    }

    @Override
    public User loadUser(String username) {
        //构造条件
        QueryWrapper<User> query = new QueryWrapper<>();
        query.lambda().eq(User::getUsername,username);
        return this.baseMapper.selectOne(query);
    }

}
